const app = getApp();
const Qiniu = require('../../utils/qiniu')
import { nowDate,getArrNotNullLength } from "../../utils/util"
const qiniuUpload = (file, fileName) => {
  return new Promise((resolve) => {
    Qiniu.upload(file, res => {
      resolve(res)
    }, () => {
      app.showNetError()
    }, {
      region: 'NCN',
      key: `qkmd/qkmingdaoapp/form/hand/${nowDate}/${fileName}.${file.split('.').pop()}`
    })
  })
}

Page({
  data: {
    imageTypes: ["左手掌心", "左手手背", "左手大拇指", "右手掌心", "右手手背", "右手大拇指"],
    showCamera: true,
    cameraPosition: 'back', // 初始使用后置摄像头
    isScrollTip: "F"
  },
  onLoad() {
    let handImageList = wx.getStorageSync('handImageList')||[]
    let handImageIndex = wx.getStorageSync('handImageIndex')||0
    let existNum = handImageList.length
    this.setData({
      handImageList,  //图片list
      handImageIndex, //活动图片下标
      existNum, //存在图片数
      isScrollTip: existNum>1?'N':'F',
      showCameraBtn: !handImageList[handImageIndex],
      nextBtn: getArrNotNullLength(handImageList) < 6 ? "确认并下一步" : "确认并提交",
      goBackBtnTop: app.globalData.menuBtnTop + app.globalData.menuBtnHeight / 2 - app.globalData.rpxWidth * 31
    })
    
  },
  onShow() {
    wx.setStorageSync('operate_step', 1)
  },
  // 拍照方法
  async takePhoto() {
    try {
      const hasPermission = await this.ensureCameraPermission();
      if (!hasPermission) return
      // 创建相机上下文
      const ctx = wx.createCameraContext();
      const res = await new Promise((resolve, reject) => {
        ctx.takePhoto({
          quality: 'high',
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            reject(err);
          }
        });
      });
      // 获取拍摄照片的临时路径
      this.saveTempImagePath(res.tempImagePath)
    } catch (err) {
      wx.showToast({
        title: '拍照出错，请稍后重试',
        icon: 'none'
      });
      console.error('拍照出错:', err);
    }
  },
  saveTempImagePath(tempImagePath) {
    let handImageList = [...this.data.handImageList]
    handImageList.splice(this.data.handImageIndex, 1, tempImagePath)
    let isScrollTip = this.data.isScrollTip=='F'&&handImageList.length==2&&!app.globalData.isReadScrollTip?"Y":(handImageList.length ==1?"F":"N")
    if(isScrollTip == 'Y') {
      app.globalData.isReadScrollTip = true
    }
    
    this.setData({
      handImageList,
      isScrollTip,
      existNum: handImageList.length,
      showCameraBtn: false
    });
    //异步上传照片
    this.upLoadImageFile(tempImagePath, this.data.handImageIndex)
  },
  //上传图片
  async upLoadImageFile(tempImagePath, handImageIndex) {
    await Qiniu.init()
    let handTypes = ["Lsx", "Lsb", "Lsz", "Rsx", "Rsb", "Rsz"]
    let imgFileName = new Date().getTime() + Math.floor(Math.random() * 10000).toString().padStart(4, '0') + handTypes[handImageIndex]
    let handImageList = [...wx.getStorageSync('handImageList')]
    let imageURLInfo = await qiniuUpload(tempImagePath, imgFileName)
    handImageList.splice(handImageIndex, 1, "https://static.rbanma.com" + imageURLInfo.imageURL)
    wx.setStorageSync('handImageList', handImageList)
    wx.setStorageSync('handImageIndex', handImageIndex)
  },
  onScrollTipBTn() {
    this.setData({
      isScrollTip: "N"
    });
  },
  async confirmAndNext() {
    let handImageIndex = this.data.existNum
    let handImageList = wx.getStorageSync('handImageList')
    if(getArrNotNullLength(handImageList) != handImageIndex) {
      let index = this.data.handImageIndex
      await this.upLoadImageFile(this.data.handImageList[index], index)
    } 
    if (handImageIndex >= 6) {
      this.navigateToUserInfoFillPage()
    } else {
      this.setData({
        showCameraBtn: true,
        handImageIndex: handImageIndex,
        nextBtn: handImageIndex < 5 ? "确认并下一步" : "确认并提交"
      })
    }
  },
  navigateToUserInfoFillPage() {
    wx.navigateTo({
      url: '/pages/userInfo-fill/userInfo-fill'
    })
  },
  cancel() {
    let handImageList = [...wx.getStorageSync('handImageList')]
    handImageList.splice(this.data.handImageIndex, 1, null)
    this.setData({
      showCameraBtn: true,
      handImageList
    })
    wx.setStorageSync('handImageList', handImageList)
    wx.setStorageSync('handImageIndex',this.data.handImageIndex)
  },
  toggleCamera: function () {
    this.setData({
      cameraPosition: this.data.cameraPosition === 'back' ? 'front' : 'back'
    });
  },
  async chooseAndUploadImage() {
    try {
      // 选择图片
      const chooseResult = await wx.p.chooseImage({
        count: 1, // 最多选择 1 张图片
        sizeType: ['original'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'] // 可以指定来源是相册还是相机，默认二者都有
      });
      // 获取拍摄照片的临时路径
      this.saveTempImagePath(chooseResult.tempFilePaths[0])
    } catch (error) {
      wx.showToast({
        title: '图片未选择',
        icon: 'none'
      });
    }
  },
  //点击数字按钮
  onNumBtn(e) {
    let handImageList = wx.getStorageSync('handImageList')
    if(getArrNotNullLength(handImageList) != this.data.existNum) return
    let handImageIndex = e.currentTarget.dataset.index
    if (!this.data.showCameraBtn && this.data.existNum > handImageIndex) {
      this.setData({
        handImageIndex
      })
    }
  },
  // 滑动改变
  onSwiperChange(e) {
    let handImageIndex = e.detail.current
    let handImageList = wx.getStorageSync('handImageList')
    if(getArrNotNullLength(handImageList) != this.data.existNum)  {
      handImageIndex = this.data.handImageIndex
    } 
    this.setData({
      handImageIndex
    })
  },
  // 相机权限检查
  async ensureCameraPermission() {
    try {
      // 获取当前权限设置
      const settingRes = await wx.p.getSetting();

      // 如果没有相机权限
      if (!settingRes.authSetting['scope.camera']) {
        // 请求相机权限
        await wx.p.authorize({
          scope: 'scope.camera'
        });
        console.log('相机权限获取成功');
        return true;
      }

      // 已有相机权限
      return true;

    } catch (error) {
      // 处理授权失败的情况
      console.error('获取相机权限失败:', error);

      // 判断是否是用户拒绝授权
      if (error.errMsg && error.errMsg.includes('auth deny')) {
        // 显示友好提示并提供前往设置的选项
        const modalRes = await wx.p.showModal({
          title: '权限申请',
          content: '拍照功能需要使用相机权限，请授予相机权限以继续使用。',
          confirmText: '去授权',
          cancelText: '暂不授权'
        });

        if (modalRes.confirm) {
          // 用户点击"去授权"，打开设置页面
          await wx.p.openSetting();

          // 检查设置是否已更改
          const newSetting = await wx.p.getSetting();
          if (newSetting.authSetting['scope.camera']) {
            console.log('用户已在设置中授予相机权限');
            this.setData({
              showCamera: true
            })
            return true;
          } else {
            wx.showToast({
              title: '权限未开启，无法使用拍照功能',
              icon: 'none',
              duration: 3000
            });
            return false;
          }
        } else {
          // 用户拒绝授权
          wx.showToast({
            title: '权限被拒绝，无法使用拍照功能',
            icon: 'none',
            duration: 3000
          });
          return false;
        }
      } else {
        // 处理其他错误
        wx.showToast({
          title: '获取权限失败，请稍后重试',
          icon: 'none',
          duration: 3000
        });
        return false;
      }
    }
  },
  // 相机错误处理方法
  cameraError(e) {
    this.setData({
      showCamera: false
    })
    const hasPermission = this.ensureCameraPermission();
    if (!hasPermission) return
    console.error('相机出错:', e.detail);
    wx.showToast({
      title: '相机出错，请检查设备',
      icon: 'none'
    });
  },
  //返回主页
  onGoBackTap() {
    wx.navigateBack()
    // wx.reLaunch({
    //   url: '/pages/index/index'
    // })
  }
})